﻿using System;
using FirstWebSite.AuthenticationServiceClient;

namespace FirstWebSite
{
    public partial class UrlGateWay : System.Web.UI.Page
    {
        private AuthenticationServiceClient.AuthenticationServiceClient client = null;

        public UrlGateWay()
        {
            client = new FirstWebSite.AuthenticationServiceClient.AuthenticationServiceClient();
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            string url = Request.QueryString["url"];

            User user = Session["User"] as User;
            if (user == null)
            {
                Response.Redirect("Login.aspx");
                return;
            }

            else if (!url.Contains("Login.aspx"))
            {
                TokenRequest tokenRequest = new TokenRequest();
                tokenRequest.User = user;
                TokenResponse tokenResponse = client.GetToken(tokenRequest);

                if (null != tokenResponse.Token && !String.IsNullOrEmpty(tokenResponse.Token.Id))
                {
                    url = url + "?token=" + tokenResponse.Token.Id;

                    //remove session after generating token
                    Session.Remove("User");
                }
            }

            if (!String.IsNullOrEmpty(url))
            {
                Session.Abandon();
                Response.Redirect(url);
            }
        }
    }
}
